package com.jt.config;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.PropertySource;
import redis.clients.jedis.HostAndPort;
import redis.clients.jedis.JedisCluster;

import java.util.HashSet;
import java.util.Set;

/**
 * @author Administrator
 * @Configuration注解标识的类为配置类
 */
@Configuration
@PropertySource("classpath:/properties/redis.properties")
public class RedisConfig {

    /**
     * 引入redis集群配置
     */
    @Value("${redis.nodes}")
    private String nodes;

    //spring整合集群
    @Bean
    public JedisCluster jedisCluster(){
        Set<HostAndPort> node = new HashSet<>();
        String[] strNodes = nodes.split(",");
        for (String strNode : strNodes) {
            String host = strNode.split(":")[0];
            int port = (Integer.parseInt(strNode.split(":")[1]));
            node.add(new HostAndPort(host,port));
        }
        return new JedisCluster(node);
    }


    /**
     * spring整合 redis 分片机制
    @Bean
    public ShardedJedis shardedJedis(){
        //1.获取每个节点的信息
        String[] strNodes = nodes.split(",");
        List<JedisShardInfo> shards = new ArrayList<>();
        //2.遍历所有Node，为List集合赋值
        for (String node : strNodes) {  //node=ip:port
            String host = node.split(":")[0];
            int port = (Integer.parseInt(node.split(":")[1])) ;
            JedisShardInfo info = new JedisShardInfo(host,port);
            shards.add(info);
        }
        ShardedJedis shardedJedis = new ShardedJedis(shards);
        return shardedJedis;
    }*/



    /*@Value("${redis.host}")
    private String host;
    @Value("${redis.port}")
    private Integer port;

    @Bean
    public Jedis jedis(){
        return new Jedis(host,port);
    }*/
}
